package com.huawei.hgip.paintgame.activity;

import java.io.IOException;
import java.net.UnknownHostException;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.huawei.hgip.paintgame.R;
import com.huawei.hgip.paintgame.adapter.MenuListAdapter;
import com.huawei.hgip.paintgame.app.ZZYYActivity;
import com.huawei.hgip.paintgame.m.data.Menu;
import com.huawei.hgip.paintgame.m.data.UserProfile;
import com.huawei.hgip.paintgame.util.RegistLoginThread;

/**
 * 应用的入口页面，菜单列表从数据库中读取
 * 
 * @author Administrator
 * 
 */
public class MainActivity extends ZZYYActivity {

	private ListView menuList;

	private MenuListAdapter menuListAdapter;

	/* add by sunlian */
	public UserProfile userProfile = new UserProfile();
	private boolean isLogin = false;

	/* add by sunlian end */

	/** Called when the activity is first created. */
	// @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// add by sunlian
		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		// 判断是否是由菜单“首页”重新启动的页面，如果是则不再次登录
		Intent intent = getIntent();
		if (null != intent) {
			// 菜单“首页”按钮的intent 传递
			// isLogin。注：不能仅根据intent是否为null来决定是否登录，因为这样2次重启程序时不会进行正常登录。
			isLogin = intent.getBooleanExtra("isLogin", false);
		}
		if (isLogin) {
			System.out.println("isLogin:" + isLogin + "!\n");
		} else {
			// 启动登录/注册线程
			System.out.println("MainThread ID:"
					+ Thread.currentThread().getId() + "!\n");
			new RegistLoginThread(this, tm).start();
		}
		// add by sunlian end

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (menuListAdapter == null) {
			menuListAdapter = new MenuListAdapter(database.getShowMenuList());
		} else {
			menuListAdapter.setMenus(database.getShowMenuList());
		}
		menuList = (ListView) findViewById(R.id.main_list);
		menuList.setAdapter(menuListAdapter);
		menuList.setOnItemClickListener(new OnItemClickListener() {

			// @Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Menu menu = menuListAdapter.getItem(position);
				if (menu != null) {
					int newClickTimes = menu.getClickTimes() + 1;
					database.updateAppClickTimes(menu.getId(), newClickTimes);
					if (!menu.isNeedUpdate()) {
						Intent i = new Intent(menu.getAction());
						try {
							startActivity(i);
						} catch (ActivityNotFoundException e) {
						}
					}
				}
			}
		});
	}

	// add by sunlian 退出登录
	@Override
	protected void onDestroy() {
		super.onDestroy();

		try {
			userProfile.userQuit();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}